const Topic = require('@/models/sys/TopicModel')

class TopicService{
    async getList(ctx:any) {
        let {page, limit=10} = ctx.query
        if (page < 1) return []
        const step = limit * (page - 1)
        const topics = await Topic.find({name: new RegExp(ctx.query.q)}).limit(limit * 1).skip(step)
        return topics
    }
    async getById(ctx:any) {
        const {fields} = ctx.query
        const str = fields.split(';').join(' +')
        const topic = await Topic.findById(ctx.params.id).select(' +' + str)
        if (!topic) { ctx.throw(404, '话题不存在') }
        return topic
    }
    async save(ctx:any) {
        const {name} = ctx.request.body
        const topic = await Topic.findOne({name})
        if (topic) {
            ctx.throw(409, '话题已存在！');
        }
        return await new Topic(ctx.request.body).save()
    }
    async update(ctx:any) {
        const topic = await Topic.findOneAndUpdate(ctx.request.body.id, ctx.request.body)
        if (!topic) {
          ctx.throw(404)
        }
        return {}
    }
}
module.exports = new TopicService()